package goconfig

import (
	"errors"
	"gitee.com/ichub/goconfig/common/base/basedto"
	"gitee.com/ichub/goconfig/common/base/baseutils/fileutils"
	"gitee.com/ichub/goconfig/common/base/baseutils/goutils"
	"go/build"
)

type GominiFilecfg struct {
	basedto.BaseEntitySingle

	LogFileBaseName string //gonats.log
	LogFileDir      string
	BasePkgName     string
	PkgRootDir      string            `json:"pkgDir"`
	RootDir         string            `json:"rootDir"`
	pkgDirs         map[string]string `json:"pkgDirs"`

	BaseEnvBathPath    string
	BaseEnvCmdBasePath string
}

func NewGominiFilecfg() *GominiFilecfg {
	var gf = &GominiFilecfg{
		pkgDirs:            make(map[string]string),
		RootDir:            fileutils.FindRootDir(),
		BaseEnvBathPath:    "BasePath",
		BaseEnvCmdBasePath: "CmdBasePath",
	}
	gf.InitProxy(gf)
	return gf
}
func Default() *GominiFilecfg {

	return NewGominiFilecfg()
}
func (self *GominiFilecfg) FindPkgRoot() (string, error) {

	if self.BasePkgName == "" {
		return "", errors.New("pkgdir is empty!")
	}
	var pkg, err = self.FindPkg(self.BasePkgName)
	self.PkgRootDir = pkg.Root
	return pkg.Root, err
}

func (self *GominiFilecfg) FindPkg(pkgPathName string) (*build.Package, error) {
	return build.Default.Import(pkgPathName, "", build.FindOnly)

}

func (self *GominiFilecfg) FindRootDir() string {
	if self.RootDir != "" {
		return self.RootDir
	}
	self.RootDir = fileutils.FindRootDir()
	return self.RootDir
}

// const BASE_PKG = "gitee.com/ichub/godi/di"
func (self *GominiFilecfg) InitPkgPath() error {

	return self.InitPkg("gitee.com/ichub/goconfig/common/configdto/basedto")
}
func (self *GominiFilecfg) InitPkg(pkg string) error {
	self.BasePkgName = pkg
	if pkgRoot, err := self.FindPkgRoot(); err == nil {

		goutils.Info(pkgRoot)
		fileutils.SetRootPkgEnv(pkgRoot)
	} else {
		return err
	}
	return nil
}
